package com.yin.ketech.common.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @author luzw
 * @version V1.0
 * @className JwtTokenUtils
 * @description TODO
 * @date 2020/6/1
 **/
public class JwtTokenUtils {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    private static final String SECRET = "yingu";
    private static final String ISS = "yingu";

    /***
     * 过期时间是3600秒，既是1个小时
     */
    public static final long EXPIRATION = 3600L;

    /***
     * 选择了记住我之后的过期时间为7天
     */
    private static final long EXPIRATION_REMEMBER = 604800L;

    /***
     * 创建token
     */
    public static String createToken(String username, long expiration) {
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .claim("username", username)
                .setIssuer(ISS)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }

    public static String cretateAccessToken(String username, boolean isRememberMe){
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        return createToken(username, expiration);
    }

    public static String cretateRefreshToken(String username, boolean isRememberMe){
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        return createToken(username, expiration * 3);
    }

    /***
     * 从token中获取用户名
     */
    public static String getUsername(String token){
        try{
            return getTokenBody(token).getSubject();
        } catch (Exception e){
            return null;
        }
    }

    public static Date getExpirationDate(String token){
        try{
            return getTokenBody(token).getExpiration();
        } catch (ExpiredJwtException e){
            return null;
        }

    }

    // 是否已过期
    public static boolean isExpiration(String token){
        try{
            return getTokenBody(token).getExpiration().before(new Date());
        }catch (Exception e){
            return true;
        }

    }

    private static Claims getTokenBody(String token){
        try{
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            return null;
        }

    }


    public static void main(String[] args) {
        String s  = cretateRefreshToken("yingu",false);
        System.out.println(s);
        String username = getUsername(s);
        System.out.println(username);
    }
}
